﻿using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Collections.Generic;

namespace YeaTrip.Comet
{
    public static class CometThreadPool
    {
        private static object state = new object();
        private static List<CometWaitThread> waitThreads = new List<CometWaitThread>();
        private static int nextWaitThread = 0;
        private static int maxWaitThreads = 0;

        internal static void QueueCometWaitRequest(CometAsyncResult request)
        {
            CometWaitThread waitThread;

            //获取下一个线程
            lock (state)
            {
                waitThread = waitThreads[nextWaitThread];
             
                nextWaitThread++;
                if (nextWaitThread == maxWaitThreads)
                    nextWaitThread = 0;
            }

            //push当前请求到该线程的待处理请求队列中
            waitThread.QueueCometWaitRequest(request);
        }

        /// <summary>
        /// 初始化Comet线程，在程序启动时调用
        /// </summary>
        /// <param name="count"></param>
        public static void CreateThreads(int count)
        {
            for (int i = 0; i < count; i++)
            {
                CometWaitThread waitThread = new CometWaitThread();
                waitThreads.Add(waitThread);
            }

            maxWaitThreads = count;
        }
    }
}
